package com.indusfo.spc.controller;



import com.indusfo.spc.pojo.ExcelErrorData;
import com.indusfo.spc.pojo.Mat;

import com.indusfo.spc.service.MatService;

import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.controller
 * @ClassName: MaterialXOController
 * @Author: 熊冰
 * @Description: 物料视图层
 * @Date: 2019/8/19 10:44
 * @Version: 1.0
 */

@Controller
@RequestMapping("/service/mat")
public class MatController {
    @Resource
    MatService matService;

    //新增
    @RequestMapping(value="insertMat")
    @ResponseBody
    public JSONObject insertMat(Mat mat){

        JSONObject json = matService.insertMat(mat) ;
        return json;

    }

    //删除启用 停用
    @RequestMapping(value = "defineMat")
    @ResponseBody
    public JSONObject delMat(Integer[] ids, Integer dataState) {
        JSONObject json = matService.deleteMat(ids, dataState);
        return json;

    }

    //更新
    @RequestMapping(value = "updateMat")
    @ResponseBody
    public JSONObject updateMat(Mat mat) {
        JSONObject json = matService.updateMat(mat);
        return json;

    }

    /**
     * 全查
     *
     * @param mat
     * @return
     */
    @RequestMapping(value = "queryMat")
    @ResponseBody
    public JSONObject queryMat(Mat mat) {
        //根据标识来判断是进行高级查询还是全查
        JSONObject json = matService.listMat(mat);
        return json;
    }


    /**
     * @author: louk
     * @Description: 高级查询接口
     * @date: 2019/10/14 20:21
     */
    @RequestMapping(value = "/advancedQuery")
    @ResponseBody
    public JSONObject advancedQuery(Mat mat) {
        JSONObject json = matService.advancedQuery(mat);
        return json;
    }

    /**
     * @author: louk
     * @Description: 物料Excel导入
     * @date: 2019/11/5 16:12
     */
    @RequestMapping("/uploadFileMat")
    @ResponseBody
    public JSONObject uploadFileMat(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

        //定义一个message对象用于向前台传输数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);

        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        List<Mat> matList=new ArrayList<>();
        List<Integer> cellList=new ArrayList<>();
        Mat mat=new Mat();
        if (wb == null) {
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    jsonObject.setMsg("未找到需要导入的数据，请确认物料信息表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认料信息表格是否保存！！！"));
                } else {
                    for (int i = 1; i <= rowCount; i++) {
                        Boolean flag=true;
                        Row row = sheet.getRow(i);
                        if(ExcelUtil.isRowEmpty(row)){
                            flag=false;
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i,"该行数据为空(原因:清空行内容时未清空彻底/未输入"));
                        }else{
                            //获取到每一行的每一列的数据
                            //物料编号
                            String vcMatCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                            //物料名称
                            String matName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                            //规格型号
                            String matModel =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
                            //物料类别
                            String matTypeName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
                            //单位
                            String matUnitName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 4, false);
                            //条码规则
                            String ruleName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 5, false);
                            //物料类型  默认成品
                            String artifactTypeIdName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 6, false);
                            //图号
                            String figureNum = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 7, false);
                            //客户代码
                            String customerName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 8, false);
                            //单位数量
                            String unitNumContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 9, false);
                            Integer unitNum = null;
                            //成品机型
                            String deviceModel = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 10, false);
                            //资源数
                            String resourceNumContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 11, false);
                            Integer resourceNum = null;
                            //生产节拍
                            String productTaktContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 12, false);
                            Integer productTakt = null;
                            //报工数量
                            String finishNumContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 15, false);
                            Integer finishNum = null;
                            //干燥时间
                            String dryDateContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 13, false);
                            Integer dryDate = null;
                            //保有量
                            String inventoryNumContent = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 14, false);
                            Integer inventoryNum = null;
                            if (!StringUtils.isBlank(unitNumContent)) {
                                if (StringUtils.isNumeric(unitNumContent)) {
                                    unitNum = Integer.valueOf(unitNumContent);
                                }else{
                                    flag=false;
                                    errorDatas.add(ExcelErrorData.getExcelErrorData(i, "单位数量不为整数"));
                                }
                            }
                            if (!StringUtils.isBlank(resourceNumContent)) {
                                if (StringUtils.isNumeric(resourceNumContent)) {
                                    resourceNum = Integer.valueOf(resourceNumContent);
                                }else{
                                    flag=false;
                                    errorDatas.add(ExcelErrorData.getExcelErrorData(i, "资源数数量不为整数"));
                                }
                            }
                            if (!StringUtils.isBlank(productTaktContent)) {
                                if (StringUtils.isNumeric(productTaktContent)) {
                                    productTakt = Integer.valueOf(productTaktContent);
                                }else{
                                    flag=false;
                                    errorDatas.add(ExcelErrorData.getExcelErrorData(i, "生产节拍不为整数"));
                                }
                            }
                            if (!StringUtils.isBlank(dryDateContent)) {
                                if (StringUtils.isNumeric(dryDateContent)) {
                                    dryDate = Integer.valueOf(dryDateContent);
                                }else{
                                    flag=false;
                                    errorDatas.add(ExcelErrorData.getExcelErrorData(i, "干燥时间不为整数"));
                                }
                            }
                            if (!StringUtils.isBlank(inventoryNumContent)) {
                                if (StringUtils.isNumeric(inventoryNumContent)) {
                                    inventoryNum = Integer.valueOf(inventoryNumContent);
                                }else{
                                    flag=false;
                                    errorDatas.add(ExcelErrorData.getExcelErrorData(i, "保有量不为整数"));
                                }
                            }
                            if (!StringUtils.isBlank(finishNumContent)) {
                                if (StringUtils.isNumeric(finishNumContent)) {
                                    finishNum = Integer.valueOf(finishNumContent);
                                }else{
                                    flag=false;
                                    errorDatas.add(ExcelErrorData.getExcelErrorData(i, "报工数量不为整数"));
                                }
                            }
                            mat = new Mat(vcMatCode, matName, matModel, resourceNum, inventoryNum,
                                    finishNum, productTakt, dryDate, deviceModel, customerName,
                                    figureNum, ruleName, matUnitName,matTypeName, unitNum,artifactTypeIdName);
                        }
                        if (flag) {
                            cellList.add(i);
                            matList.add(mat);
                        }
                    }
                    if( Optional.ofNullable(matList).isPresent() &&!matList.isEmpty()){
                        errorDatas = matService.checkExcelContentList(sheet, matList, errorDatas,cellList);
                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR) && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (Optional.ofNullable(matList).isPresent() && matList.size() > 0 && way) {
                            try {
                                matService.updateListMat(matList);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }
                }
            }
        }
        return JSONObject.build(JSONObject.SUCCESS, jsonObject.getMsg(), errorDatas);
    }

    /*@RequestMapping("/uploadFileMatTest")
    @ResponseBody
    public JSONObject uploadFileMatTest(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        List<Mat> matLists = EasyExcel.read(file.getInputStream(), Mat.class, new UploadDataLisener()).sheet().doReadSync();
        *//*File file1 = ExcelUtil.multipartFileToFile(file);
        List<Mat> matList = EasyExcel.read(file1).head(Mat.class).sheet().doReadSync();*//*
        String fileName=this.getClass().getResource("/").getPath()+"TestExport"+".xlsx";
        EasyExcel.write(fileName,Mat.class).sheet("模版").doWrite(matLists);
        return JSONObject.build(400,"导入成功",matLists);
    }*/


    /**
     * 去添加查询（产品，任务单，批次 非成品）
     */
    @RequestMapping(value = "/queryListMatToInsert")
    @ResponseBody
    public JSONObject queryListMatToInsert(Mat mat) {
        JSONObject json = matService.queryListMatToInsert(mat);
        return json;
    }

    /**
     * 去添加查询（产品，任务单，批次 成品）
     */
    @RequestMapping(value = "/queryListMatToInsertend")
    @ResponseBody
    public JSONObject queryListMatToInsertend(Mat mat) {
        JSONObject json = matService.queryListMatToInsertend(mat);
        return json;
    }
    /**
     * 去添加查询（产品，任务单，批次 成品）
     */
    @RequestMapping(value = "/testQuery")
    @ResponseBody
    public JSONObject testQuery(){
        return matService.testQuery();
    }
}
